// pages/regimental-commander/store-info/store-info.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    formData: {
      deliver_name: '',
      thumb: [],
      address: '',
      street: '',
      specificAddress: '',
      phone: '',
      reason: '',
      province_id: '',
      city_id: '',
      district_id: '',
      street_id: '',
      mapdata_address: '',
      lng: "",
      lat: "",
    },
    uploadFileUrl: 'upload.uploadPic',
    editable: false,
    areaList: {},
    areaValue: '110101',
    addressPopup: false,
    streetList: [],
    streetPopup: false
  },

  /**
   * input 数据双向绑定
   * @param {Object} e 
   */
  inputChange: function (e) {
    const { item } = e.currentTarget.dataset
    const { detail } = e
    const { formData } = this.data
    formData[item] = detail
    this.setData({ formData })
  },

  /**
   * 删除门店照片
   */
  deletePhone: function () {
    this.setData({ 'formData.thumb': [] })
  },

  afterRead: function (e) {
    const { url } = e.detail.file
    const { uploadFileUrl } = this.data
    const urlStr = app.getNetAddresss(uploadFileUrl)
    const _this = this
    wx.showLoading({ title: '上传中...' })
    wx.uploadFile({
      url: urlStr,
      filePath: url,
      name: 'file',
      success: function (res) {
        const resData = JSON.parse(res.data)
        if (resData.result == 1) {
          const { img_url } = resData.data
          _this.setData({ ['formData.thumb']: [{ url: img_url }] })
        } else {
          wx.showToast({
            title: resData.msg,
            icon: 'none'
          })
        }
      },
      complete: function () {
        wx.hideLoading()
      }
    })
  },

  /**
   * 显示/关闭popup
   * @param {Object} e 
   */
  triggerPopup(e) {
    if (!this.data.editable) return
    const { item, isshow } = e.currentTarget.dataset
    if (item == 'streetPopup' && !this.data.formData.address) {
      wx.showToast({ title: '请先选择门店地址', icon: 'none' })
      return
    }
    this.setData({
      [item]: isshow,
    })
  },

  /**
   * 地区选中确认
   * @param {Object} e 
   */
  areaConfirm(e) {
    const { values } = e.detail;
    const fieldValue = values
      .map((option) => option.name)
      .join('/');
    this.setData({
      'formData.address': fieldValue,
      areaValue: values[2].code,
      'formData.street': '',
      addressPopup: false,
      'formData.province_id': values[0].code,
      'formData.city_id': values[1].code,
      'formData.district_id': values[2].code
    })
    this.getStreetData(values[2].code)
  },

  /**
   * 获取街道列表数据
   * @param {String|Number} code 
   */
  getStreetData: function (code = '') {
    if (!code) {
      wx.showToast({ icon: 'none', title: '缺少参数', })
      return
    }
    wx.showLoading({ title: '加载中' })
    const _this = this
    let urlStr = app.getNetAddresss("member.memberAddress.street");
    urlStr += "&district_id=" + code
    app._postNetWork({
      url: urlStr,
      success: function (res) {
        const resData = res.data
        if (resData.result == 1) {
          _this.setData({ streetList: resData.data })
          let  cureentStreet = resData.data.find(item=>{
            return item.id == _this.data.formData.street_id
          })
          if(cureentStreet){
            _this.setData({
              'formData.street':cureentStreet.areaname
            })
          }
          
        } else {
          wx.showToast({ title: resData.msg })
        }
      },
      complete: function () {
        wx.hideLoading()
      }
    })
  },

  /**
   * 街道选中
   * @param {Object} e 
   */
  streetConfirm: function (e) {
    const { street = '', code = '' } = e.currentTarget.dataset
    this.setData({
      'formData.street': street,
      'formData.street_id': code,
      streetPopup: false
    })
  },
  goloc() {
    //wx.setStorageSync("ztd_temporary", this.data.formData);
    if (!this.data.editable) return
    wx.navigateTo({
      url: '/packageC/o2o/o2oLocation_loc/o2oLocation_loc?tag=selfCarryApply',
    });
  },
  /**
   * 进入编辑状态
   */
  enableEditing: function () {
    this.setData({ editable: true })
    wx.setNavigationBarTitle({
      title: '修改门店信息',
    })
  },
  /**
 * 点击提交申请 订阅消息
 */
  submitApplicationConfirm: function () {
    let self = this;
    wx.requestSubscribeMessage({
      tmplIds: ['VqlTgT2WgCI4eitOWTV_jUxA3NafUx53S_rOBHdacRE'],
      success(res) {
        self.submitApplication();
      },
      fail(err) {
        self.submitApplication();
      },
    });
  },
  /**
   * 提交申请
   */
  submitApplication: function () {

    const { formData } = this.data
    const { deliver_name, thumb, address, street, specificAddress, phone, reason, province_id, city_id, district_id, street_id,mapdata_address,lng,lat } = formData
    if (!deliver_name) {
      wx.showToast({ title: '请填写门店名称', icon: 'none' })
      return
    }
    if (!thumb.length) {
      wx.showToast({ title: '请上传门店照片', icon: 'none' })
      return
    }
    if (!address) {
      wx.showToast({ title: '请选择门店地址', icon: 'none' })
      return
    }
    if (!street) {
      wx.showToast({ title: '请选择街道', icon: 'none' })
      return
    }
    if (!specificAddress) {
      wx.showToast({ title: '请填写详细地址', icon: 'none' })
      return
    }
    if (
      app._isTextEmpty(this.data.formData.lng) ||
      app._isTextEmpty(this.data.formData.lat)
    ) {
      wx.showToast({
        icon: "none",
        title: "经纬度不能为空",
        duration: 1500,
      });
      return;
    }
    if (!phone) {
      wx.showToast({ title: '请填写手机号码', icon: 'none' })
      return
    }
    if (!reason) {
      wx.showToast({ title: '请填写修改原因', icon: 'none' })
      return
    }
    const _this = this
    const full_address = [...formData.address.split('/'), formData.street, formData.specificAddress].join(' ')
    const params = {
      deliver_name, full_address, province_id, city_id, district_id, street_id, reason,lng,lat,
      thumb: thumb.map(item => item.url),
      address: specificAddress,
      deliver_mobile: phone,
      mapdata_address
    }
    const url = app.getNetAddresss('plugin.package-deliver.frontend.Deliver.editDeliver')
    wx.showLoading({
      title: '数据提交中...',
    })
    app._postNetWork({
      url,
      data: params,
      success: function (res) {
        const resData = res.data
        if (resData.result == 1) {
          wx.showModal({
            title: '成功',
            content: '数据已提交，请等待审核',
            showCancel: false,
            confirmText: '我知道了',
            confirmColor: '#ee0a24',
            complete: (res) => {
              if (res.confirm) {
                _this.initStoreData()
                _this.setData({ editable: false })
                wx.setNavigationBarTitle({
                  title: '门店信息',
                })
              }
            }
          })
        } else {
          wx.showToast({
            icon: 'none',
            title: resData.msg,
          })
        }
      },
      complete: function () {
        wx.hideLoading()
      }
    })
  },

  /**
   * 初始化地区数据
   */
  initAreaData: function () {
    const url = app.getNetAddresss('member.member-address.address')
    const _this = this
    wx.showLoading({
      title: '获取地址信息...',
    })
    app._postNetWork({
      url,
      success: function (res) {
        const resData = res.data
        if (resData.result == 1) {
          const { province, city, district } = resData.data
          let province_list = {}
          let city_list = {}
          let county_list = {}
          province.forEach(item => {
            province_list[item.id] = item.areaname
          })
          city.forEach(item => {
            city_list[item.id] = item.areaname
          })
          district.forEach(item => {
            county_list[item.id] = item.areaname
          })
          _this.setData({
            'areaList.province_list': province_list,
            'areaList.city_list': city_list,
            'areaList.county_list': county_list
          })
        } else {
          wx.showToast({
            icon: 'none',
            title: resData.msg,
          })
        }
      },
      complete: function () {
        wx.hideLoading()
      }
    })
  },

  /**
   * 初始化门店信息
   */
  initStoreData: function () {
    const url = app.getNetAddresss('plugin.package-deliver.frontend.Deliver.getDeliver')
    const _this = this
    wx.showLoading({
      title: '获取门店信息...',
    })
    app._postNetWork({
      url,
      success: function (res) {
        const resData = res.data
        if (resData.result == 1) {
          const storeInfo = resData.data.deliver
          _this.getStreetData(storeInfo.district_id)
          const addressArray = storeInfo.full_address.split(' ')
          _this.setData({
            formData: {
              deliver_name: storeInfo.deliver_name,
              thumb: storeInfo.thumb.map(item => {
                return { url: item }
              }),
              address: addressArray.slice(0, 3).join('/'),
              street: addressArray[3],
              specificAddress: storeInfo.address,
              phone: storeInfo.deliver_mobile,
              reason: '',
              province_id: storeInfo.province_id,
              city_id: storeInfo.city_id,
              district_id: storeInfo.district_id,
              street_id: storeInfo.street_id,
              lat: storeInfo.lat,
              lng: storeInfo.lng,
              mapdata_address: storeInfo.full_address
            },
            areaValue: storeInfo.district_id
          })
        } else {
          wx.showToast({
            icon: 'none',
            title: resData.msg,
          })
        }
      },
      complete: function () {
        wx.hideLoading()
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.initAreaData()
    this.initStoreData()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    console.log('1111111111')
    try {
      let value = wx.getStorageSync('applyaddresspoint');
      if (value) {
        this.setData({
          'formData.lng': value.point.lng,
          'formData.lat': value.point.lat,
          'formData.mapdata_address': value.address,
        });
      }
    } catch (e) {
      console.log(e);
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})